﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotNet.Common.Kit;
namespace TB.Spider.Dianpu
{
    public class ShopIndex:BaseDianpu
    {
        static int _ipSuccCount = 0;
        static int _ipFailCount = 0;
        static string _ip = "本机IP";
        double vtime = 0;
        #region 采集页面返回的参数部分
        string _shopId = "";//output 
        string _xyRank = "";  //信用等级 output
        string _createDate = ""; //创建日期。output
        string _userId = ""; //用户ID  output
        string _sjName = "";//设计师   output
        string _shopTitle = ""; //标题 output
        string _dpVer = "";   //店铺版本  output
        string _templateID = ""; //模板ID output
        //string _nickName = "";  //掌柜名  output  基类中定义
        public string DPVer
        {
            get { return _dpVer; }
        }
        public string TemplateID
        {
            get { return _templateID; }
        }
        //public string NickName
        //{
        //    get { return _nickName; }
        //}
        public string ShopTitle
        {
            get { return _shopTitle; }
        }
        public string SJName
        {
            get { return _sjName; }
        }
        public string ShopID
        {
            get { return _shopId; }
        }

        public string XyRank
        {
            get { return _xyRank; }
        }
        public string CreateDate
        {
            get { return _createDate; }
        }

        public string UserID
        {
            get { return _userId; }
        }
        #endregion  
        #region  事件定义
        public event TBEventHandler PrintLog;
        public event TBEventHandler IPShift;
        #endregion
        private string MyGetHtml(HttpHelper http,HttpItem item,ref double vtime)
        {
            string ret = "";
            System.Net.WebHeaderCollection head = new System.Net.WebHeaderCollection();
            HttpResult result=new HttpResult();
            DateTime d1 = DateTime.Now;
            result=http.GetHtml(item);
            DateTime d2 = DateTime.Now;
            ret = result.Html;
            head = result.Header;
            vtime = (d2 - d1).Ticks / 10000;
            return ret;
        }

        public int GetDianpuInfo(string url)
        {
            TBShowLogEventArgs e = new TBShowLogEventArgs();
            bool vfunFlag = true; //访问函数标识作为WHILE中失败次数，ipSuccCoun-1
            base.ShopUrl = url;
            int ret = 0;
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem();
            item.URL = url;
            item.Allowautoredirect = true; //自动跳转
            item.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50215;)";
            string htmlStr = MyGetHtml(http, item,ref vtime);  //循环变量初始化值。同样在while中也应该有这四行，以便于退出循环
            _ipSuccCount++;
            e.Msg = e.Msg = "IP:" + _ip + "\r\nIP访问速度:" + vtime/1000+" 秒";
            IPShift(this, e);
            HtmlDocHelper htmlDoc = new HtmlDocHelper(htmlStr);
            string hdNode = htmlDoc.GetNode("//div[@id='hd']");
            string bdNode = htmlDoc.GetNode("//div[@id='bd']");
            DateTime closeInitTime = DateTime.Now; //标识关机时间起点。
            while (hdNode == "" && bdNode == "")  //没有找到店铺信息 对于最原始的店铺有多个这样标识节点，但可以找到店铺 http://shop35417311.taobao.com  http://shop72187389.taobao.com
            {
                string msg = htmlDoc.GetHtmlTitle();
                if (msg == "")
                {
                    msg = htmlDoc.GetHtmlBody();
                    if (msg == "")
                        msg = htmlStr;
                }
               // LocLoggerHelper.LogToFile("ShopIndex:GetDianpuInfo():while  Title:"+msg+"ShopUrl:"+ShopUrl);
                e.Msg = "ShopIndex:GetDianpuInfo():while  Title:" + msg + "ShopUrl:" + ShopUrl;
                PrintLog(this, e);
                _ipFailCount++;
                if(vfunFlag)
                    _ipSuccCount--;
                vfunFlag = false;
                DateTime closeEndTime = DateTime.Now;
                IniHelper ini = new DotNet.Common.Kit.IniHelper("ShiftIP.ini");
                Dictionary<string, string> dict = ini.SectionValuesEx("ReConnectRouter"); //读取INI换IP条件 重启或者代理 
                if (ShiftIPHelper.ExistShiftIp(dict, msg))  //有换IP的条件存在。
                {
                    int ipCount = 0;
                    int proxyFlag=0;
                    ShiftIPHelper.UpdateIpInfo(_ip, ref vtime, ref _ipSuccCount, ref _ipFailCount);
                    _ip=ShiftIPHelper.GetShiftIp(ref ipCount,ref proxyFlag);  //标识是不是本机IP
                    e.Msg = "IP:" + _ip + "\r\nIP访问速度" + vtime/1000 + " 秒"; ;
                    IPShift(this, e);
                    if (proxyFlag == 1)
                        item.ProxyIp = _ip;
                    if(proxyFlag==0 ||_ip=="本机IP")
                        item.ProxyIp = "";
                    _ipSuccCount = 0;
                    _ipFailCount = 0;
                }
                if (closeEndTime > closeInitTime.AddMinutes(1)) //在循环中等待5分钟
                {
                    ini = new IniHelper("HtmlNodeXPath.ini");
                    if (ini.GetKeyValue("ProxyUseFlag", "closeSys") == "0")  //进入关机程序
                    {
                        //e.ErrMessage = "开始循环时间：" + closeInitTime + "  结束循环关机时间" + closeEndTime;

                        //logger.LogToFile(e.ErrPosition + "--超时5分钟关机--" + htmlStrTitle);
                    }
                    if (ini.GetKeyValue("ProxyUseFlag", "closeSys") == "1")  //换是个机IP访问
                    {//对于不关机程序，超时5分钟则退出本次循环
                        break;  //http://shop71906861.taobao.com/这样的找不到店铺信息，退出本次while
                    }
                }
                htmlStr = MyGetHtml(http, item, ref vtime);
                htmlDoc = new HtmlDocHelper(htmlStr);
                hdNode = htmlDoc.GetNode("//div[@id='hd']");
                bdNode = htmlDoc.GetNode("//div[@id='bd']");
            }
            string title=htmlDoc.GetHtmlTitle();
            if (title != "")//对其他网络异常的补充判断。保证程序不要出错，但可以会漏掉该条记录
            {
                //最原始店铺:标题中含有“淘宝网”但不含有“首页” <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
                if (title.Contains("淘宝网") && (!title.Contains("首页")) && (htmlStr.Trim().Substring(0, 15).ToLower() != "<!doctype html>"))
                {
                    //e.ErrMessage = "掌柜--" + this._nickName + "--首页--" + this._shopUrl + "--HTML代码不满足条件";
                    //e.ErrPosition = "ShopIndex:InitTaobaoTmallDp()=>if (titleTemp.Contains(淘宝网)";
                    //this.ShowErrHandler(lblInfo, e);
                    //logger.WriteErrorLog(e.ErrPosition + e.ErrMessage);
                }
                else
                {
                    ret = InitTaobaoTmallDp(htmlStr);
                }
            }
            else
            {
                //e.ErrMessage = "掌柜--" + this._nickName + "--首页--" + this._shopUrl + "--Title不满足条件";
                //e.ErrPosition = "ShopIndex:InitDianpuIndex()=>else";
                //this.ShowErrHandler(lblInfo, e);
                //logger.WriteErrorLog(e.ErrPosition + e.ErrMessage);
            }
            //PrintLog(this, e);
            return ret;
        }

        #region 将HTML格式化到类的字段中
        private int InitTaobaoTmallDp(string htmlStr)
        {
            HtmlDocHelper htmlDoc = new HtmlDocHelper(htmlStr);
            try
            {
                string title = htmlDoc.GetHtmlTitle();
                _shopTitle = title.Split('-')[1];
                string script = htmlDoc.GetNode("//head/script");//DocumentNode.SelectNodes("//script")[0].InnerText;
                
                //此处注意子串的长度设置，由于网络传输数据的加密会使其更长。
                this._shopId = script.Substring(script.IndexOf("shopId"), 30).Split(new char[] { ':', ',', '"' })[3];
                this._userId = script.Substring(script.IndexOf("userId"), 30).Split(new char[] { ':', ',', '"' })[3];
                this.Nickname = System.Web.HttpUtility.UrlDecode(script.Substring(script.IndexOf("user_nick"), 200).Split(new char[] { ':', ',', '"' })[3]);
                this._sjName = System.Web.HttpUtility.UrlDecode(script.Substring(script.IndexOf("design_nick"), 150).Split(new char[] { ':', ',', '"' })[3]);
                if (_sjName != "")  //此处得到模板ID  
                {//此处代码要考虑各种版本页面的HTML代码。
                    if (htmlStr.Contains("id=\"copyright\""))
                    {
                        this._templateID = htmlDoc.GetNodeAttr("//div[@id='copyright']/descendant::span/descendant::a", "href").Split('=')[1]; ;
                        //if (htnSpan.Contains("店铺设计"))
                        //{   //descendant 选取当前节点的所有后代元素（子、孙等）  以当前DIV为根 所有SPAN 
                        //    htnSpan = htmlDoc.GetNode("//div[@id='copyright']/descendant::span/descendant::a");
                        //}
                    }
                    if (htmlStr.Contains("id=\"wangpu-copyright\""))
                    {//descendant 选取当前节点的所有后代元素（子、孙等）
                        this._templateID = htmlDoc.GetNodeAttr("//div[@id='wangpu-copyright']/descendant::span/descendant::a", "href").Split('=')[1];
                        //string htnSpan = htmlDoc.GetNode("//div[@id='wangpu-copyright']/descendant::span/descendant::a");
                    }
                }
                else
                {
                    _templateID = "";
                }
                if (title.Contains("天猫Tmall.com"))  //天猫店铺没有这三个值
                {
                    this._xyRank = "0";
                    this._dpVer = "天猫店铺";
                    this._createDate = "";
                }
                if (title.Contains("淘宝网"))
                {
                    //没有等级情况的考虑不够
                    this._xyRank = htmlDoc.GetNodeAttr("//img[@class='rank']", "src");
                    //HtmlAgilityPack.HtmlNodeCollection rankNodeCollection = htmlDoc.DocumentNode.SelectNodes("//img[@class='rank']");
                    if (_xyRank == "")
                        _xyRank = "<11";
                    else                             // http://pics.taobaocdn.com/newrank/s_blue_5.gif
                        _xyRank = _xyRank.Split('/')[4];
                    this._dpVer = DianpuVer(htmlStr);
                    this._createDate = CreateDianpuDate(htmlStr);
                }
            }
            catch (Exception ex)
            {
                LocLoggerHelper.WriteException(ex);
                return 0;
            }
            return 1;
        }

        /// <summary>
        /// 根据页面信息得到相应的版本  
        /// </summary>
        /// <param name="ver">传入的HTML信息</param>
        /// <returns>2012新旺铺专业版   2012新旺铺基础版  天猫店铺  旺铺扶植版  旺铺标准版  旺铺拓展版  旺铺旗舰版</returns>
        private string DianpuVer(string html)
        {
            string retVer = "";
            if (html.Contains("http://img04.taobaocdn.com/tps/i4/T1prA2XhlhXXcgU5U6-113-21.png"))
                retVer = "2012新旺铺基础版";
            else if (html.Contains("http://img01.taobaocdn.com/tps/i1/T1lKXaXp4hXXcgU5U6-113-21.png"))
                retVer = "2012新旺铺专业版";
            else if (html.Contains("标准版"))
                retVer = "旺铺标准版";
            else if (html.Contains("扶植版"))
                retVer = "旺铺扶植版";
            else if (html.Contains("拓展版"))
                retVer = "旺铺拓展版";
            else if (html.Contains("旗舰版"))
                retVer = "旺铺旗舰版";
            else
                retVer = "天猫店铺";
            return retVer;
        }

        private string CreateDianpuDate(string htmlStr)
        {
            string createTime = "";
            //此处如此判断会有问题，有时候可能页面含有这样的串。不科学的方法，分析两者的页面可知，
            //对于老的店铺含有“店铺信息”有这样节结点<div class="shop-details"><h4>店铺信息</h4>
            //新的店铺有<div class="bd-left shop-intro">
            HtmlDocHelper htmlDoc = new HtmlDocHelper(htmlStr);
            if (htmlStr.Contains("class=\"bd-left shop-intro\""))  //新店铺  http://shop105393410.taobao.com/  
            {
                string date= htmlDoc.GetNodeIndex("//div[@class='bd-left shop-intro']/descendant::span", 4);
                if(date!="")
                    createTime = DateTime.Parse(date).ToShortDateString();
            }
            else    // http://shop2004.taobao.com/  <li class="setuptime"><span>创店时间：</span>2004-02-22</li>
            {
                createTime = htmlDoc.GetNode("//li[@class='setuptime']").Split('：',':')[1];
            } 
            return createTime;
        }
        #endregion
    }
}
